import React, { useState } from 'react';
import { PERMISSION_ENUM, getSdk } from '../bpm-sdk';
import Modal from '../modal';

export default () => {
  const sdk = getSdk();
  const [eventData, setEventData] = useState<any>();
  const [visible, setVisible] = useState(false);
  const handleClick = async () => {
    const eventData: any = await sdk.getActionInfo(PERMISSION_ENUM.BACK);
    console.log(eventData);
    setEventData(eventData);
    setTimeout(() => {
      setVisible(true);
    }, 300);
  };

  const onBack = (backDealType = 2, targetNodeId?: string) => {
    sdk.emitAction({
      submitType: PERMISSION_ENUM.BACK,
      submitParams: {
        // 回退参数
        targetNodeId,
        backDealType,
      },
    });
  };

  const btnClass =
    'px-3 py-2 text-sm mr-2 mt-2 font-semibold text-white rounded-md shadow-lg bg-cyan-500 shadow-cyan-500/50 focus:outline-none';
  return (
    <>
      <button type="button" onClick={handleClick} className={btnClass}>
        回退自定义
      </button>
      <Modal
        visible={visible && !!eventData?.info}
        onCancel={() => {
          setVisible(false);
        }}
      >
        <div>请选择你需要回退的节点</div>
        <button
          type="button"
          onClick={() => {
            onBack(0);
          }}
          className={btnClass}
        >
          回退上节点
        </button>
        <button
          onClick={() => {
            onBack(1);
          }}
          type="button"
          className={btnClass}
        >
          回退发起者
        </button>
        {eventData?.info &&
          Object.keys(eventData.info).map((k) => {
            return (
              <button
                onClick={() => {
                  onBack(2, k);
                }}
                key={k}
                type="button"
                className={btnClass}
              >
                {eventData.info[k]}
              </button>
            );
          })}
      </Modal>
    </>
  );
};
